<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>第四节课</title>
		<style type="text/css">
			/*去除原来样式*/
			
			* {
				padding: 0;
				margin: 0;
			}
			
			.container {
				width: 100vw;
				height: 100vh;
				display: flex;
				/*
				 * 将边框设置在中间
				 */
				align-items: center;
				justify-content: center;
			}
			
			canvas {
				width: 500px;
				height: 500px;
				border: 1px solid #333333;
			}
			
			/*.anniu{
				width: 100px;
				height: 100px;
				
			}*/
		</style>
	</head>

	<body>
		<!--<img id="img" src="cut.jpeg" alt="" />-->
		<div class="container">
			<canvas id="canvas" width="700" height="700"></canvas>
			<div class="anniu">
				<input type="button" name="" id="start" value="开始" />
				<input type="button" name="" id="stop" value="停止" />
				
				
				<input type="button" name="" id="color" value="换颜色" />
				<br />
				<input type="button" name="" id="clear" value="隐藏（单击开始显示）" />
			</div>	
			
		</div>
	</body>

	<script>
		
		window.onload = function(){
			
			let oCanvas = document.getElementById("canvas");
			let pen = oCanvas.getContext("2d");
			
			let m=100;
				n=100;
				speed=10;
			pen.fillStyle = "cornflowerblue";
			pen.fillRect(0,0,m,n);
			
			let timer;
			let num=0;
				down=0;
				left=0;
				up=0;
				s=1;
			let start = document.getElementById("start");
			
			function move(x,y){
				pen.clearRect(0,0,m,n);
				pen.translate(x,y);
				pen.fillRect(0,0,m,n);
			}
			
			start.onclick = function(){
				clearInterval(timer);
				
				timer = setInterval(function(){
					//pen.translate(0,10);
					
					
					
					if(num<=(canvas.width-m)){
						move(speed,0);
						num+=speed;
					}
					
					if(num>(canvas.height-n)&&down<=(canvas.height-n)){
						move(0,speed);
						down+=speed;
					}
					if(down>(canvas.height-n)&&left<=(canvas.width-m)){
						move(-speed,0);
						left+=speed;
						
					}
					if(left>(canvas.width-m)&&up<=(canvas.height-n)){
						move(0,-speed);
						up+=speed;
						
						
					}
					if(up>(canvas.height-n)){
						num=0;
						down=0;
						left=0;
						up=0;
					}
					
				},50);
				
				
			}
			
			let stop = document.getElementById("stop");
			stop.onclick = function(){
				clearInterval(timer);
			}
			
			let clear = document.getElementById("clear");
			clear.onclick = function(){
				clearInterval(timer);
				pen.clearRect(0,0,canvas.width,canvas.height);
				//pen.fillStyle = "cornflowerblue";
				//pen.fillRect(0,0,100,100);
			}
			
			let color = document.getElementById("color");
			color.onclick = function(){
				pen.fillStyle = "#"+Math.round(Math.random()*1000000);
			}
			
		}
			
	</script>

</html>